<?php

namespace App\Jobs\Topic;

use App\Exceptions\BusinessException;
use App\Models\Theme;
use App\Models\Topic;
use App\Models\TopicsDrafts;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;

class Publish implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function handle()
    {
        // 发布草稿箱的帖子
        TopicsDrafts::where('status', 0)
            ->where('publish_date', '<=', now()->format('Y-m-d H:i:s'))
            ->chunkById(500, function ($topics) {
                foreach ($topics as $draft) {

                    try {
                        DB::beginTransaction();

                        $themeIdArr = [];
                        $themes = explode(',', $draft->themes);

                        foreach ($themes as $name) {
                            $model = Theme::where('name', $name)->first();
                            if ($model) {
                                $model->increment('use_sum');

                            } else {
                                $model = Theme::create(['name' => $name, 'use_sum' => 1, 'mini_type' => $draft->mini_type]);
                            }
                            $themeIdArr[] = $model->id;
                        }

                        $topic = Topic::create([
                            'member_id'   => $draft->member_id,
                            'title'       => $draft->title,
                            'content'     => $draft->content,
                            'tag_id'      => $draft->tag_id,
                            'files'       => $draft->files,
                            'relay_count' => $draft->relay_count,
                            'fav_count'   => $draft->fav_count,
                            'is_hot'      => $draft->is_hot,
                            'status'      => 1,
                            'mini_type'   => $draft->mini_type,
                        ]);
                        $topic->topicTheme()->sync($themeIdArr);

                        $draft->update(['status' => 1]);

                        DB::commit();
                    } catch (\Throwable $e) {
                        DB::rollBack();

                        log_exception('定时发布帖子异常', $e);

                        throw new BusinessException('发布帖子异常');
                    }
                }
            });
    }
}

